#!/usr/bin/perl -w

BEGIN {
	push(@INC,"/home/modules/");
};
use strict;
use utf8;
use Excel::Writer::XLSX;
use Text::Iconv;
use Encode;
use DBI;
use Cwd 'abs_path';
use JSON;

abs_path($0)=~/^(.*[\\\/])/;
my $logpath="$1/logs/json_table_to_xlsx.log";
sub mywarn {
	open OUT,">>$logpath" or print STDERR "Could not write to $logpath\n";
	foreach (@_) {
		print OUT $_;
		print OUT "\n" unless $_=~/\n$/;
#		print STDERR $_;
#		print STDERR "\n" unless $_=~/\n$/;
	}
	close OUT;
}

sub mydie {
	mywarn(@_);
	exit(1);
}

# Parameters - login, password, database, ss_id, $output_filename

{
	$SIG{__WARN__}=\&mywarn;
	$SIG{__DIE__}=\&mydie;
	$SIG{INT}=\&mydie;

	warn "\n\n".localtime()."\n";
	warn $0." ".join(" ",@ARGV)."\n";
	die "Wrong parameters\n" unless @ARGV==1;
	my ($jsonfile)=@ARGV;
	
	my $xlsfile=$jsonfile;
	$xlsfile=~s/\.json$/.xlsx/;
	
	my $data;
	open IN,$jsonfile or die "Can not open $jsonfile";
	{local $/;$data=<IN>;}
	close IN;
	$data=decode_json($data);
	if (-f $xlsfile) {
		unlink($xlsfile) or die "Can not delete $xlsfile";
	}
	my $workbook = Excel::Writer::XLSX->new($xlsfile);
	my $worksheet = $workbook->add_worksheet("export");
	for (my $y=0;$y<@$data;$y++) {
		for (my $x=0;$x<@{$data->[$y]};$x++) {
			my $value=$data->[$y]->[$x];
			Encode::_utf8_on($value);
			$worksheet->write($y,$x,$value);
		}
	}
}

